package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
//    @Autowired
//    private UserMapper userMapper;
//    @Autowired
//    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.selectById(id);

        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);//通知类型 1来单提醒 2客户催单
        map.put("orderId", id);//订单id
        map.put("content","订单号:" + order.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repetition(Long id) {
        Orders oldOrder = orderMapper.selectById(id);

        if (oldOrder == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        AddressBook addressBook = addressBookMapper.selectById(oldOrder.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Orders newOrder = new Orders();
        BeanUtils.copyProperties(oldOrder, newOrder);
        newOrder.setId(null);
        newOrder.setNumber(String.valueOf(System.currentTimeMillis()));
        newOrder.setStatus(Orders.PENDING_PAYMENT);
        newOrder.setPayStatus(Orders.UN_PAID);
        newOrder.setOrderTime(LocalDateTime.now());
        newOrder.setEstimatedDeliveryTime(oldOrder.getEstimatedDeliveryTime().plusMinutes(60));
        orderMapper.insert(newOrder);

        orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", oldOrder.getId()))
                .forEach(detail -> {
                    if (detail.getDishId() != null && StatusConstant.DISABLE.equals(dishMapper.selectById(detail.getDishId()).getStatus())) {
                        throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
                    }

                    if (detail.getSetmealId() != null && StatusConstant.DISABLE.equals(setmealMapper.selectById(detail.getSetmealId()).getStatus())) {
                        throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
                    }

                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(detail, orderDetail);
                    orderDetail.setId(null);
                    orderDetail.setOrderId(newOrder.getId());
                    orderDetailMapper.insert(orderDetail);
                });

        paySuccess(newOrder.getNumber());
    }

    @Override
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = (Page<Orders>) orderMapper.selectList(new QueryWrapper<Orders>()
                .eq(ordersPageQueryDTO.getUserId() != null, "user_id", ordersPageQueryDTO.getUserId())
                .eq(ordersPageQueryDTO.getStatus() != null, "status", ordersPageQueryDTO.getStatus())
                .eq(ordersPageQueryDTO.getNumber() != null, "number", ordersPageQueryDTO.getNumber())
                .eq(ordersPageQueryDTO.getPhone() != null, "phone", ordersPageQueryDTO.getPhone())
                .ge(ordersPageQueryDTO.getBeginTime() != null, "order_time", ordersPageQueryDTO.getBeginTime())
                .le(ordersPageQueryDTO.getEndTime() != null, "order_time", ordersPageQueryDTO.getEndTime())
                .orderByDesc("order_time"));
        List<OrderVO> orderVOList = page.stream().map(orders -> {
                    OrderVO orderVO = new OrderVO();
                    BeanUtils.copyProperties(orders, orderVO);
                    orderVO.setOrderDetailList(orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orders.getId())));
                    StringBuilder stringBuilder = new StringBuilder();
                    for (OrderDetail orderDetail : orderVO.getOrderDetailList()) {
                        stringBuilder.append(orderDetail.getName()).append(" * ").append(orderDetail.getNumber()).append(",");
                    }
                    if (stringBuilder.length() > 0) {
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }
                    orderVO.setOrderDishes(stringBuilder.toString());
                    return orderVO;
                }).collect(Collectors.toList());

        return new PageResult(page.getTotal(), orderVOList);
    }

    public PageResult listCurrUser(OrdersPageQueryDTO ordersPageQueryDTO){
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        return list(ordersPageQueryDTO);
    }


    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(
                new QueryWrapper<ShoppingCart>().eq("user_id", BaseContext.getCurrentId())
        );
        if (CollectionUtils.isEmpty(shoppingCartList)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        log.info(ordersSubmitDTO.toString());
        log.info(order.toString());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        orderMapper.insert(order);

        orderDetailMapper.insert(shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetail.setId(null);
            return orderDetail;
        }).collect(Collectors.toList()));

        shoppingCartMapper.delete(
                new QueryWrapper<ShoppingCart>().eq("user_id", BaseContext.getCurrentId())
        );

        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //跳过微信支付逻辑
//        // 当前登录用户
//        User user = userMapper.selectById(BaseContext.getCurrentId());
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖测试订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException(MessageConstant.ORDER_ALREADY_PAID);
//        }
//
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.selectOne(new QueryWrapper<Orders>().eq("number", outTradeNo));

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.updateById(orders);

        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);//通知类型 1来单提醒 2客户催单
        map.put("orderId", orders.getId());//订单id
        map.put("content","订单号:" + outTradeNo);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    public OrderStatisticsVO getOrderStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectCount(new QueryWrapper<Orders>().eq("status", Orders.TO_BE_CONFIRMED)).intValue());
        orderStatisticsVO.setConfirmed(orderMapper.selectCount(new QueryWrapper<Orders>().eq("status", Orders.CONFIRMED)).intValue());
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectCount(new QueryWrapper<Orders>().eq("status", Orders.DELIVERY_IN_PROGRESS)).intValue());
        return orderStatisticsVO;
    }

    @Override
    public void complete(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(orders);
    }

    @Override
    public void confirm(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);
    }

    @Override
    public OrderVO getById(Long id) {
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orders.getId())));
        List<String> orderDishes = new ArrayList<>();
        for (OrderDetail orderDetail : orderVO.getOrderDetailList()) {
            orderDishes.add(orderDetail.getName() + " * " + orderDetail.getNumber());
        }
        orderVO.setOrderDishes(StringUtils.join(orderDishes, ','));
        return orderVO;
    }

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateById(orders);
    }
}
